package com.etgraph.recap.msof.template;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelTemplateStyle {
	
	private Workbook wb;
	private CellStyle style;
	private Font font;
	
	public ExcelTemplateStyle(Workbook wb){
		this.wb = wb;
		this.style = this.wb.createCellStyle();
		this.style.setWrapText(true);
		this.font = wb.createFont();
	}
	
	public ExcelTemplateStyle appendFontBold(){
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setFont(font);
		return this;
	}
	
	public ExcelTemplateStyle appendFontRead(){
		font.setColor(HSSFFont.COLOR_RED);
		style.setFont(font);
		return this;
	}
	
	public ExcelTemplateStyle appendFontWhite(){
		font.setColor(HSSFFont.SS_SUPER);
		style.setFont(font);
		return this;
	}
	
	public ExcelTemplateStyle appendFillPattern(){
		style.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		return this;
	}
	
	public ExcelTemplateStyle appendDateFormate(){
		style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
		return this;
	}
	
	/**
	 * set wrap text false
	 * default is true
	 * @return this
	 */
	public ExcelTemplateStyle appendNoWrapText(){
		style.setWrapText(false);
		return this;
	}
	
	public CellStyle getCellStyle(){
		return this.style;
	}
	
	/**
	 * After sheet created call this method
	 * @param columns which columns should be auto size
	 * @param sheet the sheet
	 */
	public void setAutoSize(Set<Integer> columns, Sheet sheet){
		for (Integer column : columns) {
			List<Integer> list = new ArrayList<Integer>();
			for (Row row : sheet) {
				Cell cell = row.getCell(column);
				if(cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING){
					String cellText = cell.getStringCellValue();
					int textLength = countTextLength(cellText);
					list.add(textLength);
				}
			}
			int maxWidth = getMaxWidthColumn(column, list);
			sheet.setColumnWidth(column, maxWidth);
		}
	}

	private int countTextLength(String cellText) {
		if(cellText != null && !"".equals(cellText)){
			return (cellText.getBytes().length + 2) * 256;
		}
		return 0;
	}

	private int getMaxWidthColumn(Integer column, List<Integer> list) {
		int first = 0;
		if(list != null && !list.isEmpty()){
			first = list.get(0);
			for (int i = 1; i < list.size(); i++) {
				if(first < list.get(i)){
					first = list.get(i);
					if(first/256>100){
						return 100*256;
					}
				}
			}
		}
		return first;
	}
}
